package m.jclecai.com.activity.follow;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.LayoutRes;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.adapter.base.ViewHolerAdapter;
import m.jclecai.com.adapter.holder.ViewHolder;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.ProofBean;
import m.jclecai.com.bean.Response.ResHotPeopleInfo;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.inter.OnCautionDialogConfirmListener;
import m.jclecai.com.listener.Callback;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.view.CautionDialog;

/**
 * 这里是个人购买的记录介绍
 */
public class HotPeopleInfoActivity extends BaseActivity {


    @BindView(R.id.iv_user_icon)
    ImageView mIvUserIcon;


    @BindView(R.id.iv_user_rank)
    ImageView mIvUserRank;

    @BindView(R.id.tv_nickname)
    TextView mTvNickname;
    @BindView(R.id.tv_fans)
    TextView mTvFans;
    @BindView(R.id.tv_win_total_money)
    TextView mTvWinTotalMoney;
    @BindView(R.id.tv_unit_award)
    TextView mTvUnitAward;
    @BindView(R.id.tv_seven_day_award)
    TextView mTvSevenDayAward;
    @BindView(R.id.tv_thirty_day_award)
    TextView mTvThirtyDayAward;
    @BindView(R.id.tv_value)
    TextView mTvValue;

    @BindViews({R.id.iv_term_one,
            R.id.iv_term_two,
            R.id.iv_term_three,
            R.id.iv_term_four,
            R.id.iv_term_five,})
    ImageView[] mIvTermImgs;
    //关注
    @BindView(R.id.ll_follow)
    LinearLayout mLlFollow;

    @BindView(R.id.tv_follow_statue)
    TextView mTvFollowStatue;

    @BindView(R.id.tv_custom_order)
    TextView mTvCustomOrder;

    //定制跟单；
    @BindView(R.id.ll_custom_follow)
    LinearLayout mLlCustomFollow;

    public static final String HOT_PEOPLE_ID = "userId";


    private PullToRefreshListView mRefreshListView;
    private ListView mListView;
    private HotPeopleInfoAdapter mHotPeopleInfoAdapter;
    private ResHotPeopleInfo mResHotPeopleInfo;
    private String mHotPeopleId;

    @Override
    protected int getContentView() {
        return R.layout.activity_hot_people_info;
    }

    @Override
    protected void initLoadingView() {
        super.initLoadingView();
        mRefreshListView = (PullToRefreshListView) findViewById(R.id.prl_list_view);
        mListView = mRefreshListView.getRefreshableView();
        mListView.addHeaderView(View.inflate(this, R.layout.header_hot_people_info, null));
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("红人详情");
        leftOptionText("");
    }

    @Override
    protected void initData() {
        super.initData();

        mHotPeopleInfoAdapter = new HotPeopleInfoAdapter();
        mRefreshListView.setAdapter(mHotPeopleInfoAdapter);

        mHotPeopleId = getIntent().getStringExtra(HOT_PEOPLE_ID);

        requestData(mHotPeopleId);

    }

    public void requestData(String hotPeopleId){
        requestHeader(hotPeopleId);
        requestHotOrder(hotPeopleId);
    }

    private void requestHotOrder(String hotPeopleId) {
        //这里我们要请求的是热门的跟单；
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("id",mHotPeopleId);
        showDialog();
        HttpManager.postAsyn(Constant_Url.FOLLOW_HOT_ORDER, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {

                DisPlay("网络异常!");
                dissDialog();

            }

            @Override
            public void onResponse(String response) {

                try {
                    if (!TextUtils.isEmpty(response)) {

                        mResHotPeopleInfo = FastOk.get(response, ResHotPeopleInfo.class);
                        if (mResHotPeopleInfo!=null) {

                            if("0".equals(mResHotPeopleInfo.getStatus())){

                                mHotPeopleInfoAdapter.refresh(mResHotPeopleInfo.getRecords());
                            }else{
                                DisPlay(mResHotPeopleInfo.getMessage());
                            }

                        } else {
                            DisPlay("网络异常!");
                        }
                    } else {
                        DisPlay("网络异常!");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    DisPlay("网络异常!");
                }
            }
        },paramsMap);

    }

    private void requestHeader(String hotPeopleId) {

        showDialog();
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("id", hotPeopleId);
        paramsMap.put("user",PreferenceUtil.getUserName(this));
        HttpManager.postAsyn(Constant_Url.HOT_PEOPLE_INFO, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlay("网络异常!");
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                if (!TextUtils.isEmpty(response)) {

                    mResHotPeopleInfo = FastOk.get(response, ResHotPeopleInfo.class);
                    if (mResHotPeopleInfo!=null) {

                        if("0".equals(mResHotPeopleInfo.getStatus())){

                            updateHeader();
                           // mHotPeopleInfoAdapter.refresh(mResHotPeopleInfo.getRecords());
                        }else{
                            DisPlay(mResHotPeopleInfo.getMessage());
                        }

                    } else {
                        DisPlay("网络异常!");
                    }
                } else {
                    DisPlay("网络异常!");
                }
            }
        }, paramsMap);

    }

    /**
     * 这里我们是用来刷新头部的数据的
     */
    private void updateHeader() {
        //头部
        mTvFans.setText("粉丝:" + mResHotPeopleInfo.getFans());
        mTvWinTotalMoney.setText("总共中奖:" + mResHotPeopleInfo.getWinmoneys_total());
        mTvNickname.setText(mResHotPeopleInfo.getUsername());
        Glide.with(this).load(mResHotPeopleInfo.getUser_face()).into(mIvUserIcon);

        if (mResHotPeopleInfo.getUser_rank()>0) {
            mIvUserRank.setVisibility(View.VISIBLE);
        }else{
            mIvUserRank.setVisibility(View.INVISIBLE);
        }

        //中间的那一行
        mTvUnitAward.setText(mResHotPeopleInfo.getPayback_total());
        mTvSevenDayAward.setText(mResHotPeopleInfo.getMilitary());
        mTvThirtyDayAward.setText(mResHotPeopleInfo.getMilitary_total());
        mTvValue.setText(mResHotPeopleInfo.getAll_winmoneys_total());
        //近5期的状况；
        for (int i = 0; i < mIvTermImgs.length; i++) {
            if (i < mResHotPeopleInfo.getWinstr().size()) {
                if (mResHotPeopleInfo.getWinstr().get(i).equals("0")) {
                    mIvTermImgs[i].setImageResource(R.drawable.follow_status5_nowin);
                } else {
                    mIvTermImgs[i].setImageResource(R.drawable.follow_status5_win);
                }
            } else {
                mIvTermImgs[i].setVisibility(View.INVISIBLE);
            }

        }
        //判断是否已经关注或者已经定制跟单了
        if ("1".equals(mResHotPeopleInfo.getAttention())) {
            mTvFollowStatue.setText("已关注");
        }else{
            mTvFollowStatue.setText("关注");
        }

        if ("1".equals(mResHotPeopleInfo.getFollowid())) {

            mTvCustomOrder.setText("已定制");

        }else{
            mTvCustomOrder.setText("定制跟单");
        }

    }


    public class HotPeopleInfoAdapter extends ViewHolerAdapter<HotPeopleViewHolder> {

        public List<ResHotPeopleInfo.HotPeopleOrderBean> mData = new ArrayList<>();


        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public HotPeopleViewHolder onCreateViewHolder(int position, ViewGroup parent) {
            return new HotPeopleViewHolder(parent.getContext(), R.layout.item_hot_people_info);
        }

        @Override
        public void onBindViewHolder(int position, HotPeopleViewHolder hotPeopleViewHolder) {
            hotPeopleViewHolder.init(mData.get(position));
        }

        public void clear() {
            mData.clear();
            notifyDataSetChanged();
        }

        public void refresh(List<ResHotPeopleInfo.HotPeopleOrderBean> datas) {
            mData.clear();
            addData(datas);
        }

        public void addData(List<ResHotPeopleInfo.HotPeopleOrderBean> datas) {
            mData.addAll(datas);
            notifyDataSetChanged();
        }
    }

    public class HotPeopleViewHolder extends ViewHolder {

        @BindView(R.id.tv_group_buy_title)
        TextView mTvGroupBuyTitle;

        @BindView(R.id.tv_group_buy_time)
        TextView mTvGroupBuyTime;

        @BindView(R.id.tv_least)
        TextView mTvLeast;

        @BindView(R.id.tv_group_buy_des)
        TextView mTvGroupBuyDes;

        @BindView(R.id.tv_group_buy_money)
        TextView mTvGroupBuyMoney;

        @BindView(R.id.tv_follow_number)
        TextView mTvFollowNumber;

        @BindView(R.id.tv_follow)
        TextView mTvFollow;

        @BindView(R.id.rl_award_number)
        TextView mRlAwardNumber;

        @BindView(R.id.rl_award_bg)
        RelativeLayout mRlAwardBg;


        public HotPeopleViewHolder(Context context, @LayoutRes int resource) {
            super(context, resource);
        }

        public void init(final ResHotPeopleInfo.HotPeopleOrderBean hotPeopleOrder) {
            mTvGroupBuyTitle.setText(hotPeopleOrder.getLotteryname());


            Date parse = null;
            try {
                parse = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(hotPeopleOrder.getEndtime());
            } catch (ParseException e) {
                e.printStackTrace();
            }

            String endTime = new SimpleDateFormat("MM-dd hh:mm").format(parse);
            if (TextUtils.isEmpty(endTime)) {
                endTime=hotPeopleOrder.getEndtime();
            }

            mTvGroupBuyTime.setText(endTime+" 截止 ");
            mTvLeast.setText(hotPeopleOrder.getFollow_minmoney() + "元起投");
            mTvGroupBuyDes.setText(hotPeopleOrder.getTitle());

            mTvGroupBuyMoney.setText("自购金额:"+hotPeopleOrder.getOne_money() + "元");
            mTvFollowNumber.setText("跟单:"+hotPeopleOrder.getFollow_count() + "人");


           if ("1".equals(hotPeopleOrder.getState())) {
                mRlAwardBg.setVisibility(View.VISIBLE);
                //已撤单
                mTvFollow.setVisibility(View.INVISIBLE);
                mRlAwardBg.setBackgroundResource(R.drawable.follow_no_win_img);
                mTvFollow.setOnClickListener(null);
               mRlAwardNumber.setVisibility(View.INVISIBLE);
            } else if ("2".equals(hotPeopleOrder.getState())) {
                //未中奖
                mRlAwardBg.setVisibility(View.VISIBLE);
                mRlAwardBg.setBackgroundResource(R.drawable.follow_no_win_img);
                mTvFollow.setVisibility(View.INVISIBLE);
                mRlAwardNumber.setVisibility(View.INVISIBLE);
                mTvFollow.setOnClickListener(null);
            } else if("3".equals(hotPeopleOrder.getState())){
                //已经中奖
                mRlAwardBg.setVisibility(View.VISIBLE);
                mRlAwardBg.setBackgroundResource(R.drawable.follow_win);
                mRlAwardNumber.setVisibility(View.VISIBLE);
                mRlAwardNumber.setText("￥"+hotPeopleOrder.getWin_money());
                mTvFollow.setVisibility(View.INVISIBLE);
                mTvFollow.setOnClickListener(null);

                mTvFollow.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //这里要执行的逻辑就是立即跟单
                        startActivity(HotOrderDetailActivity.getIntent(HotPeopleInfoActivity.this, hotPeopleOrder.getId()));
                    }
                });
            }else{
                //这里表示是可跟单；
                mRlAwardBg.setVisibility(View.INVISIBLE);

                mRlAwardNumber.setVisibility(View.INVISIBLE);

               if(hotPeopleOrder.getCan_follow()>0){
                   mTvFollow.setVisibility(View.VISIBLE);

                   mTvFollow.setOnClickListener(new OnClickListener() {
                       @Override
                       public void onClick(View v) {
                           //这里要执行的逻辑就是立即跟单
                           startActivity(HotOrderDetailActivity.getIntent(HotPeopleInfoActivity.this, hotPeopleOrder.getId()));
                       }
                   });

               }else{
                   mTvFollow.setVisibility(View.INVISIBLE);
                   mTvFollow.setOnClickListener(null);
               }
            }

            setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = HotOrderDetailActivity.getIntent(HotPeopleInfoActivity.this, hotPeopleOrder.getId());
                    startActivity(intent);
                }
            });

        }
    }

    //关注
    @OnClick(R.id.ll_follow)
    public void onClickFollow(View view) {

        showDialog();
        checkLogin(new Callback() {

            @Override
            public void callbackSuccess() {
                super.callbackSuccess();
                doFollowRequest();
            }

            @Override
            public void callbackField() {
                super.callbackField();
                dissDialog();
            }
        });
    }

    private void doFollowRequest() {
        final HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("user", PreferenceUtil.getUserName(this));
        paramsMap.put("password", PreferenceUtil.getPassword(this));
        paramsMap.put("type", mTvFollowStatue.getText().equals("已关注")?"del":"add");
        paramsMap.put("id", mHotPeopleId);

        HttpManager.postAsyn(Constant_Url.FOLLOW_HOT_PEOPLE, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay("网络异常");
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                if (!TextUtils.isEmpty(response)) {

                    ProofBean proofBean = FastOk.get(response, ProofBean.class);
                    if ("0".equals(proofBean.getStatus())) {
                        DisPlay(proofBean.getMessage());
                        String followStatue = mTvFollowStatue.getText().toString().equals("关注") ? "已关注" : "关注";
                        mTvFollowStatue.setText(followStatue);
                    } else {
                        DisPlay(proofBean.getMessage());
                    }
                } else {
                    DisPlay("网络异常!!!");
                }
            }
        }, paramsMap);
    }

    //定制跟单
    @OnClick(R.id.ll_custom_follow)
    public void onClickCustomFollow(View view) {
        String s = mTvCustomOrder.getText().toString();
        if("已定制".equals(s)){
            //这里我们要先取消才能定制；这里我们弹出一个对话框；
            CautionDialog CautionDialog = new CautionDialog(this, "取消定制？", new OnCautionDialogConfirmListener() {
                @Override
                public void onCancelListener() {
                }

                @Override
                public void onConfirmListener() {
                    //取消定制；
                    requestCustomCancelOrder();
                }
            });
            CautionDialog.show();
        }else {
            startActivity(CustomFollowOrderActivity.getIntent(this,mHotPeopleId));
        }
    }

    /**
     * 这里是需要登陆的；
     * 取消定制状态
     */
    private void requestCustomCancelOrder() {

        final HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("user",PreferenceUtil.getUserName(this));
        paramsMap.put("password",PreferenceUtil.getPassword(this));
        paramsMap.put("id",mHotPeopleId);

        showDialog();
        HttpManager.postAsyn(Constant_Url.CANCEL_HOT_PEOPLE_OREDER, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay("网络异常!!!");
            }

            @Override
            public void onResponse(String response) {
                //这里我们要做一个操作就是判断是否取消成
                if (!TextUtils.isEmpty(response)) {

                    ProofBean proofBean = FastOk.get(response, ProofBean.class);
                    if(proofBean!=null && proofBean.getStatus().equals("0")){
                            DisPlay("取消成功!!!");
                        mTvCustomOrder.setText("定制跟单");
                    }else{
                        if(proofBean!=null){
                            DisPlay(proofBean.getMessage());
                        }else{
                            DisPlay("网络异常！！！");
                        }
                    }

                }else{
                    DisPlay("网络异常!!!");
                }
                dissDialog();
            }
        },paramsMap);

    }

    public static Intent getIntent(Context context, String hotPeopleId) {
        Intent intent = new Intent(context, HotPeopleInfoActivity.class);

        intent.putExtra(HOT_PEOPLE_ID, hotPeopleId);

        return intent;
    }
}
